package com.lenovo.smarttraffic.ui.activity.stage6;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.SensorData;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class MyTrafficActivity extends BaseActivity {

    private Toolbar toolbar;
    private TextView user_tv;

    private ListView listView;
    private MyTrafficAdapter adapter;

    private LinearLayout env_parent;
    private TextView pm25_tv;
    private VideoView video;
    private TextView light_tv, light_tv2;
    private ProgressBar light_progress;
    private TextView res_curr_tv;

    private CheckedTextView tv1, tv2;

    private Handler handler = new Handler();

    public static NotificationManager manager;

    @Override
    protected int getLayout() {
        return R.layout.activity_my_traffic;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        toolbar = findViewById(R.id.toolbar);
        user_tv = findViewById(R.id.user_tv);
        toolbar.setNavigationOnClickListener(v -> finish());
        user_tv.setText("当前用户：" + MainActivity.userName);

        listView = findViewById(R.id.listView);

        env_parent = findViewById(R.id.env_parent);
        pm25_tv = findViewById(R.id.pm25_tv);
        video = findViewById(R.id.video);

        MediaController localMediaController = new MediaController(this);
        video.setMediaController(localMediaController);
        video.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video));

        light_tv = findViewById(R.id.light_tv);
        light_tv2 = findViewById(R.id.light_tv2);
        light_progress = findViewById(R.id.light_progress);
        res_curr_tv = findViewById(R.id.res_curr_tv);


        tv1 = findViewById(R.id.tv1);
        tv2 = findViewById(R.id.tv2);

        tv1.setOnClickListener(v -> {
            if (!tv1.isChecked()) {
                tv1.setChecked(true);
                tv2.setChecked(false);

                tv1.setTypeface(Typeface.DEFAULT_BOLD);
                tv2.setTypeface(Typeface.DEFAULT);

                listView.setVisibility(View.VISIBLE);
                env_parent.setVisibility(View.GONE);
            }
        });
        tv2.setOnClickListener(v -> {
            if (!tv2.isChecked()) {
                tv1.setChecked(false);
                tv2.setChecked(true);

                tv1.setTypeface(Typeface.DEFAULT);
                tv2.setTypeface(Typeface.DEFAULT_BOLD);

                listView.setVisibility(View.GONE);
                env_parent.setVisibility(View.VISIBLE);
            }
        });

        if (adapter == null) {
            adapter = new MyTrafficAdapter();
            listView.setAdapter(adapter);
        }

        refresh1.run();
        refresh2.run();
    }

    private Runnable refresh1 = new Runnable() {
        @Override
        public void run() {
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
            handler.postDelayed(refresh1, 1000);
        }
    };

    private Runnable refresh2 = new Runnable() {
        @SuppressLint("SetTextI18n")
        @Override
        public void run() {
            if (env_parent != null) {
                HttpUtils.post("get_all_sense", new HttpUtils().add("UserName", MainActivity.userName), response -> {
                    SensorData sensorData = new Gson().fromJson(response.toString(), SensorData.class);
                    int pm25 = sensorData.getPM25();
                    int light = sensorData.getLightIntensity();

                    pm25_tv.setText("PM2.5当前值：" + pm25 + "\n友情提示：" + (pm25 > 200 ? "不适合出行" : "适合出行"));
                    video.setVisibility(pm25 > 200 ? View.VISIBLE : View.INVISIBLE);
                    light_tv.setText("光照强度当前值：" + light + "\n光照强度上限值：" + 3190 + "\n光照强度下限值：" + 1100);
                    if (light < 1100 || light > 3190) {
                        light_tv2.setText("友情提示：不适合出行");
                    } else {
                        light_tv2.setText("友情提示：适合出行");
                    }
                    light_progress.setProgress(light);

                    res_curr_tv.setText(light + "");
                    res_curr_tv.setTranslationX(((float) light / 4290) * 450);

                    if (manager != null && (light < 1100 || light > 3190)) {
                        NotificationCompat.Builder builder;
                        int channelId = 1;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Android 8.0适配
                            NotificationChannel channel = new NotificationChannel(String.valueOf(channelId),
                                    "阈值警告", NotificationManager.IMPORTANCE_HIGH);
                            manager.createNotificationChannel(channel);
                            builder = new NotificationCompat.Builder(MyTrafficActivity.this, String.valueOf(channelId));
                        } else {
                            builder = new NotificationCompat.Builder(MyTrafficActivity.this);
                        }
                        builder.setContentTitle("光照强度报警")
                                .setContentText(light < 1100 ? "光照较弱，出行请开灯" : "光照较强，出行请戴墨镜")
                                .setWhen(System.currentTimeMillis())
                                .setSmallIcon(R.mipmap.car3)//通知显示的小图标，只能用alpha图层的图片进行设置
                                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.car3));

                        Notification notification = builder.build();
                        //channelId为本条通知的id
                        manager.notify(channelId, notification);
                    }

                });
                handler.postDelayed(refresh2, 3000);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        manager = null;
    }
}

class MyTrafficAdapter extends BaseAdapter {

    private NotificationManager manager = MyTrafficActivity.manager;

    private List<boolean[]> flags = new ArrayList<>(5);//Store is in counting
    private List<int[]> times = new ArrayList<>(5);//Store counting time

    public MyTrafficAdapter() {
        //Init data
        for (int i = 0; i < 5; i++) {
            flags.add(new boolean[]{false, false});
            times.add(new int[]{0, 0});
        }
    }

    @Override
    public int getCount() {
        return 5;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_my_traffic, parent, false);
            holder.info_tv = convertView.findViewById(R.id.info_tv);
            holder.info2_tv = convertView.findViewById(R.id.info2_tv);
            holder.img_parent1 = convertView.findViewById(R.id.img_parent1);
            holder.img_parent2 = convertView.findViewById(R.id.img_parent2);
            holder.time1_tv = convertView.findViewById(R.id.time1_tv);
            holder.time2_tv = convertView.findViewById(R.id.time2_tv);
            holder.btn1 = convertView.findViewById(R.id.btn1);
            holder.btn2 = convertView.findViewById(R.id.btn2);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        int id = position + 1;

        HttpUtils.post("get_road_status", new HttpUtils().setParam("RoadId", id), response -> {
            int status = response.getInt("Status");

            if (manager != null && status > 3) {
                NotificationCompat.Builder builder;
                int channelId = 3;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Android 8.0适配
                    NotificationChannel channel = new NotificationChannel(String.valueOf(channelId),
                            "道路拥堵警告", NotificationManager.IMPORTANCE_HIGH);
                    manager.createNotificationChannel(channel);
                    builder = new NotificationCompat.Builder(parent.getContext(), String.valueOf(channelId));
                } else {
                    builder = new NotificationCompat.Builder(parent.getContext());
                }
                builder.setContentTitle("道路拥堵警告")
                        .setContentText(id + "号路口处于拥挤堵塞状态，请选择合适的路线")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.car3)//通知显示的小图标，只能用alpha图层的图片进行设置
                        .setLargeIcon(BitmapFactory.decodeResource(parent.getContext().getResources(), R.mipmap.car3));

                Notification notification = builder.build();
                //channelId为本条通知的id
                manager.notify(channelId, notification);
            }
        });

        HttpUtils.post("get_trafficlight_config", new HttpUtils().setParam("TrafficLightId", id).setParam("UserName", MainActivity.userName),
                resp -> {
                    int red = (int) resp.get("RedTime");
                    int green = (int) resp.get("GreenTime");
                    int yellow = (int) resp.get("YellowTime");

                    int t1 = (position % 2 == 0 ? green : red);
                    int t2 = (position % 2 == 0 ? yellow : green);

                    holder.info_tv.setText("路口：" + id + "\n" +
                            "配置信息   " + "绿灯" + green + "秒" + "  黄灯" + yellow + "秒" + "  红灯" + red + "秒");
                    holder.img_parent1.setBackgroundResource(position % 2 == 0 ? R.mipmap.red_bg_03 : R.mipmap.red_bg_01);
                    holder.img_parent2.setBackgroundResource(position % 2 == 0 ? R.mipmap.red_bg_02 : R.mipmap.red_bg_03);


                    boolean[] flag = flags.get(position);
                    int[] time = times.get(position);

                    if (!flag[0] && !flag[1]) {
                        holder.info2_tv.setText("横向状态   " + t1 + "秒       纵向状态：" + t2 + "秒");
                    } else if (!flag[0]) {
                        holder.info2_tv.setText("横向状态   " + t1 + "秒       纵向状态：" + time[1] + "秒");
                    } else if (!flag[1]) {
                        holder.info2_tv.setText("横向状态   " + time[0] + "秒       纵向状态：" + t2 + "秒");
                    } else {
                        holder.info2_tv.setText("横向状态   " + time[0] + "秒       纵向状态：" + time[1] + "秒");
                    }

                    if (!flag[0]) {
                        holder.time1_tv.setText("" + t1);
                    } else {
                        holder.time1_tv.setText(time[0] + "");
                    }
                    if (!flag[1]) {
                        holder.time2_tv.setText("" + t2);
                    } else {
                        holder.time2_tv.setText(time[1] + "");
                    }

                    holder.btn1.setOnClickListener(v -> {
                        if (!flag[0]) {
                            flags.get(position)[0] = true;
                            times.get(position)[0] = 30;
                        }
                    });
                    holder.btn2.setOnClickListener(v -> {
                        if (!flag[1]) {
                            flags.get(position)[1] = true;
                            times.get(position)[1] = 30;
                        }
                    });

                    //Clear flag
                    if (time[0] == 0) {
                        flag[0] = false;
                    }
                    if (time[1] == 0) {
                        flag[1] = false;
                    }

                    //Counting time
                    if (flag[0] && time[0] > 0) {
                        times.get(position)[0]--;
                    }
                    if (flag[1] && time[1] > 0) {
                        times.get(position)[1]--;
                    }
                });

        if (MainActivity.userName.equals("admin")) {//Admin only
            convertView.setOnClickListener(v -> {
                View view = View.inflate(parent.getContext(), R.layout.dialog_my_traffic, null);
                View close = view.findViewById(R.id.close);
                EditText red_et = view.findViewById(R.id.red_et);
                EditText yellow_et = view.findViewById(R.id.yellow_et);
                EditText green_et = view.findViewById(R.id.green_et);
                Button set_btn = view.findViewById(R.id.set_btn);
                Button cancel_btn = view.findViewById(R.id.cancel_btn);

                AlertDialog ad = new AlertDialog.Builder(parent.getContext())
                        .setView(view)
                        .show();

                close.setOnClickListener(v1 -> ad.dismiss());
                cancel_btn.setOnClickListener(v1 -> ad.dismiss());
                set_btn.setOnClickListener(v12 -> {
                    int red = Utils.parseInt(red_et.getText().toString());
                    int yellow = Utils.parseInt(yellow_et.getText().toString());
                    int green = Utils.parseInt(green_et.getText().toString());

                    if (red < 1 || red > 30 || yellow < 1 || yellow > 30 || green < 1 || green > 30) {
                        ToastUtils.showToast(v.getContext(), "请输入正确的值");
                    } else {
                        HttpUtils.post("set_trafficlight_config", new HttpUtils().setParam("TrafficLightId", id)
                                        .setParam("RedTime", red).setParam("GreenTime", green).setParam("YellowTime", yellow)
                                        .setParam("UserName", MainActivity.userName),
                                response -> {
                                    if (Utils.getResult(response)) {
                                        ToastUtils.showToast(v.getContext(), id + "号路口的红绿灯配置信息成功");
                                        ad.dismiss();
                                    } else {
                                        ToastUtils.showToast(v.getContext(), "配置失败请重新提交");
                                    }
                                });
                    }
                });
            });
        }

        return convertView;
    }

    static class ViewHolder {
        TextView info_tv, info2_tv;
        LinearLayout img_parent1, img_parent2;
        TextView time1_tv, time2_tv;
        Button btn1, btn2;
    }
}